Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: switching networks bug #4770

Merged
merged 7 commits into from
Oct 28, 2024
Merged

FIX: switching networks bug #4770

merged 7 commits into from
Oct 28, 2024

Conversation

mateodaza
Copy link
Member

@mateodaza mateodaza commented Sep 24, 2024

Summary by CodeRabbit

  • New Features

    • Improved network switching functionality for enhanced user experience.
    • Added support for dynamically handling network changes based on user actions.
  • Bug Fixes

    • Refactored control flow for network item clicks to ensure correct network switching.
  • Documentation

    • Updated interface definitions to reflect new properties and methods for better clarity.

Copy link

vercel bot commented Sep 24, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
giveth-dapps-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 23, 2024 8:12am

Copy link
Contributor

coderabbitai bot commented Sep 24, 2024

Walkthrough

The changes involve refactoring the network switching logic within the SwitchNetwork component and enhancing the GeneralWalletProvider to manage a new state variable for pending network IDs. A new function, handleNetworkItemClick, has been created to streamline click handling for network items. Additionally, the GeneralWalletProvider now includes a mechanism to switch chains dynamically based on user interactions, improving the overall control flow for network management.

Changes

Files Change Summary
src/components/modals/SwitchNetwork.tsx Introduced handleNetworkItemClick function to centralize network item click logic. Updated interface ISwitchNetworkModal to include setPendingNetworkId from useGeneralWallet. Refactored inline logic for clarity.
src/providers/generalWalletProvider.tsx Added pendingNetworkId state variable and setPendingNetworkId function to GeneralWalletContext. Integrated useSwitchChain from wagmi for network switching. Implemented useEffect to monitor and handle network changes.

Possibly related PRs

  • Fix network modal issue #4807: The changes in the DonateWrongNetwork.tsx component involve optimizing modal closing logic related to network switching, which is relevant to the refactoring of network handling in the SwitchNetwork.tsx component.
  • Fix/one time donation switch network #4837: This PR modifies the DonateWrongNetwork.tsx component to include conditional logic for network switching based on the wallet's chain type, directly relating to the network switching functionality enhanced in the SwitchNetwork.tsx component.

Suggested reviewers

  • MohammadPCh
  • HrithikSampson
  • CarlosQ96

Poem

In the meadow where networks play,
A rabbit hops and twirls away.
With clicks and chains, we dance in glee,
New paths to explore, oh, what a spree!
Pending IDs, we’ll switch with flair,
Hopping through networks, without a care! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mateodaza mateodaza changed the title FIX: switching chains bug FIX: switching networks bug Sep 24, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Outside diff range and nitpick comments (1)
src/components/modals/SwitchNetwork.tsx (1)

62-71: LGTM: New handleNetworkItemClick function

The new function centralizes the network switching logic, improving code organization and readability. It correctly handles the special case for Solana chains, which aligns with the PR objectives to fix the switching chains bug.

Consider adding a comment explaining why we close the modal for Solana chains:

 if (walletChainType === ChainType.SOLANA) {
   setPendingNetworkId(networkId);
   handleSingOutAndSignInWithEVM();
-  closeModal(); // Close the modal since we cannot control the wallet modal
+  // Close the modal since we're redirecting to sign in with EVM and can't control the wallet modal
+  closeModal();
 } else {
   switchChain?.({ chainId: networkId });
   closeModal();
 }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between bc9a866 and f9e2750.

Files selected for processing (2)
  • src/components/modals/SwitchNetwork.tsx (4 hunks)
  • src/providers/generalWalletProvider.tsx (7 hunks)
Additional comments not posted (7)
src/components/modals/SwitchNetwork.tsx (3)

45-50: LGTM: Interface update for useGeneralWallet

The ISwitchNetworkModal interface has been correctly updated to include setPendingNetworkId from the useGeneralWallet hook. This change aligns with the new functionality for handling Solana chains.


85-85: LGTM: Integration of handleNetworkItemClick

The new handleNetworkItemClick function is correctly integrated into the NetworkItem component's onClick handler. This change simplifies the JSX and improves code readability by moving the logic to a separate function.


Line range hint 31-85: Summary: Effective solution for switching chains bug

The changes introduced in this PR effectively address the switching chains bug by:

  1. Introducing a new handleNetworkItemClick function that centralizes the network switching logic.
  2. Handling the special case for Solana chains, which requires signing out and signing in with EVM.
  3. Updating the ISwitchNetworkModal interface and component to support the new functionality.

These changes improve code organization, readability, and maintainability while fixing the reported issue.

To ensure the changes are consistent across the codebase, let's verify the usage of setPendingNetworkId:

Verification successful

Verified: The setPendingNetworkId function is correctly used within the codebase and is appropriately encapsulated without being exported from generalWalletProvider.tsx. No issues were found regarding removed or replaced code.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of setPendingNetworkId in the codebase

# Test: Search for setPendingNetworkId usage
echo "Searching for setPendingNetworkId usage:"
rg --type typescript --type tsx 'setPendingNetworkId'

# Test: Check if setPendingNetworkId is exported from the generalWalletProvider
echo "\nChecking if setPendingNetworkId is exported from generalWalletProvider:"
rg --type typescript --type tsx 'export.*setPendingNetworkId' 'src/providers/generalWalletProvider'

Length of output: 471


Script:

#!/bin/bash
# Description: Verify the usage of setPendingNetworkId in the codebase

# Test: Search for setPendingNetworkId usage
echo "Searching for setPendingNetworkId usage:"
rg --type ts --type tsx 'setPendingNetworkId'

# Test: Check if setPendingNetworkId is exported from the generalWalletProvider
echo "\nChecking if setPendingNetworkId is exported from generalWalletProvider:"
rg --type ts --type tsx 'export.*setPendingNetworkId' 'src/providers/generalWalletProvider'

Length of output: 441


Script:

#!/bin/bash
# Description: Verify the usage of setPendingNetworkId in the codebase using file glob patterns

# Test: Search for setPendingNetworkId usage
echo "Searching for setPendingNetworkId usage:"
rg 'setPendingNetworkId' -g "*.ts" -g "*.tsx"

# Test: Check if setPendingNetworkId is exported from the generalWalletProvider
echo "\nChecking if setPendingNetworkId is exported from generalWalletProvider:"
rg 'export.*setPendingNetworkId' 'src/providers/generalWalletProvider' -g "*.ts" -g "*.tsx"

Length of output: 1009


Script:

#!/bin/bash
# Description: Verify the usage and export of setPendingNetworkId in the codebase using file glob patterns

# Test: Search for setPendingNetworkId usage
echo "Searching for setPendingNetworkId usage:"
rg 'setPendingNetworkId' -g "*.ts" -g "*.tsx"

# Test: Check if setPendingNetworkId is exported from the generalWalletProvider.tsx
echo "\nChecking if setPendingNetworkId is exported from generalWalletProvider.tsx:"
rg 'export.*setPendingNetworkId' 'src/providers/generalWalletProvider.tsx' -g "*.ts" -g "*.tsx"

Length of output: 945

src/providers/generalWalletProvider.tsx (4)

17-17: Importing useSwitchChain is Appropriate

The addition of useSwitchChain from 'wagmi' library is necessary for implementing the network switching functionality.


61-61: Addition of setPendingNetworkId to Context Interface

The method setPendingNetworkId is correctly added to the IGeneralWalletContext interface to manage pending network changes.


98-100: Initialization of pendingNetworkId State Variable

The pendingNetworkId state variable is properly initialized with a default value of null, and its type is correctly set to number | null.


424-424: Including setPendingNetworkId in Context Value

The setPendingNetworkId function is correctly added to the contextValue, enabling components consuming the context to request a network switch.

Comment on lines +275 to +280
useEffect(() => {
if (walletChainType === ChainType.EVM && pendingNetworkId !== null) {
switchChain?.({ chainId: pendingNetworkId });
setPendingNetworkId(null);
}
}, [walletChainType, pendingNetworkId]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle Asynchronous switchChain Call and Potential Errors

The switchChain function returned by useSwitchChain is asynchronous and may throw an error if the chain switch fails. Currently, it's called without await or error handling inside the useEffect, which could lead to unhandled promise rejections and unexpected behavior.

Consider modifying the code to handle the asynchronous call and catch any errors:

 useEffect(() => {
-  if (walletChainType === ChainType.EVM && pendingNetworkId !== null) {
-    switchChain?.({ chainId: pendingNetworkId });
-    setPendingNetworkId(null);
-  }
+  const performSwitchChain = async () => {
+    if (walletChainType === ChainType.EVM && pendingNetworkId !== null) {
+      try {
+        await switchChain?.({ chainId: pendingNetworkId });
+      } catch (error) {
+        console.error('Error switching chain:', error);
+      } finally {
+        setPendingNetworkId(null);
+      }
+    }
+  };
+  performSwitchChain();
 }, [walletChainType, pendingNetworkId]);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
if (walletChainType === ChainType.EVM && pendingNetworkId !== null) {
switchChain?.({ chainId: pendingNetworkId });
setPendingNetworkId(null);
}
}, [walletChainType, pendingNetworkId]);
useEffect(() => {
const performSwitchChain = async () => {
if (walletChainType === ChainType.EVM && pendingNetworkId !== null) {
try {
await switchChain?.({ chainId: pendingNetworkId });
} catch (error) {
console.error('Error switching chain:', error);
} finally {
setPendingNetworkId(null);
}
}
};
performSwitchChain();
}, [walletChainType, pendingNetworkId]);

@@ -76,6 +77,7 @@
handleSignOutAndShowWelcomeModal: async () => {},
isOnSolana: false,
isOnEVM: false,
setPendingNetworkId: () => {},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Inconsistent Function Signature for setPendingNetworkId

The default implementation of setPendingNetworkId in GeneralWalletContext does not match the interface signature. The interface expects (id: number | null) => void, but the default value is setPendingNetworkId: () => {}, which accepts no parameters. This inconsistency could lead to type errors or unexpected behavior.

Apply the following diff to fix the inconsistency:

 export const GeneralWalletContext = createContext<IGeneralWalletContext>({
   // ...other context values
   handleSignOutAndShowWelcomeModal: async () => {},
   isOnSolana: false,
   isOnEVM: false,
-  setPendingNetworkId: () => {},
+  setPendingNetworkId: (id: number | null) => {},
 });

Committable suggestion was skipped due to low confidence.

Copy link
Collaborator

@MohammadPCh MohammadPCh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mateodaza Thanks, Please resolve the conflicts and also the coderabbit suggestions.

@mateodaza
Copy link
Member Author

@MohammadPCh ready! sorry your comment skipped my head last week 👍🏼

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
src/components/modals/SwitchNetwork.tsx (2)

48-50: LGTM: New props enhance functionality

The addition of setPendingNetworkId, handleSignOutAndSignInWithSolana, and chain from the useGeneralWallet hook enhances the component's functionality. These additions suggest improved state management for pending network changes and support for Solana blockchain.

Consider adding a comment explaining the purpose of these new props for better code readability.


63-72: LGTM: Improved network switching logic

The new handleNetworkItemClick function is a great addition. It centralizes the network switching logic, improving code organization and readability. The function handles different wallet types (Solana and EVM) appropriately, enhancing the component's flexibility.

Consider adding error handling for the switchChain call, as network switching can sometimes fail due to various reasons (e.g., user rejection, network issues).

Here's a suggested improvement:

const handleNetworkItemClick = async (networkId: number) => {
  try {
    if (walletChainType === ChainType.SOLANA) {
      setPendingNetworkId(networkId);
      await handleSingOutAndSignInWithEVM();
    } else {
      await switchChain({ chainId: networkId });
    }
    closeModal();
  } catch (error) {
    console.error('Failed to switch network:', error);
    // Handle the error (e.g., show an error message to the user)
  }
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f9e2750 and 3f39ea7.

📒 Files selected for processing (1)
  • src/components/modals/SwitchNetwork.tsx (4 hunks)
🧰 Additional context used
🔇 Additional comments (3)
src/components/modals/SwitchNetwork.tsx (3)

31-33: LGTM: New interface enhances type safety

The introduction of ISwitchNetworkModal interface is a good addition. It extends IModal and includes optional properties desc and customNetworks, which enhances type safety and allows for more flexible prop passing to the SwitchNetwork component.


86-86: LGTM: Simplified onClick handler

The update to use handleNetworkItemClick in the NetworkItem's onClick handler is a good refactoring. It simplifies the JSX and improves code readability by moving the logic to a separate function.


Line range hint 1-180: Overall assessment: Improved network switching functionality and code structure

The changes to the SwitchNetwork component significantly enhance its functionality and improve code organization. Key improvements include:

  1. Introduction of the ISwitchNetworkModal interface for better type safety.
  2. Addition of Solana support through new props from useGeneralWallet.
  3. Centralization of network switching logic in the handleNetworkItemClick function.
  4. Simplified onClick handler for NetworkItem.

These changes make the component more flexible, easier to maintain, and capable of handling different wallet types. The code structure improvements also enhance readability and maintainability.

Consider adding comprehensive error handling and user feedback mechanisms to further improve the robustness of the network switching process.

Copy link
Collaborator

@MohammadPCh MohammadPCh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @mateodaza LGTM
Did you read the rabbitCodeAi suggestions? Does it make the code better?

@mateodaza
Copy link
Member Author

Thanks @mateodaza LGTM Did you read the rabbitCodeAi suggestions? Does it make the code better?

yes... they add more verbose
is that ok to skip?

@MohammadPCh
Copy link
Collaborator

@mateodaza Yeah, Sure ;)

@MohammadPCh MohammadPCh merged commit 02a85a3 into develop Oct 28, 2024
3 checks passed
@MohammadPCh MohammadPCh deleted the changing-network-bug branch October 28, 2024 15:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: QA
Development

Successfully merging this pull request may close these issues.

2 participants